package com.ruoyi.kafka.domain;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.Instant;
import java.util.Map;

/**
 * @ClassName MessageEnvelope
 * @Description 通用消息封装。为保证“开箱即跑”，这里额外带上 payloadClass，消费者据此把 payload 转回强类型。
 * @Author li yang
 * @Date 2025/9/18 16:05
 * @Version 1.0
 */
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@NoArgsConstructor
@AllArgsConstructor
public class MessageEnvelope<T> {

    private String id;
    private String type;
    private String version;
    private Instant timestamp;
    private String source;
    private String correlationId;

    /** 业务负载（先反序列化为 Map/LinkedHashMap，再在消费者中转回 T） */
    private T payload;

    /** 负载对应的 class 全名（如 com.example.demo.dto.OrderCreatedEvent） */
    private String payloadClass;

    private Map<String, String> headers;

    public static <T> MessageEnvelope<T> of(String id, String type, String version,
                                            String source, String correlationId, T payload) {
        return new MessageEnvelope<>(id, type, version, Instant.now(), source, correlationId,
                payload, payload != null ? payload.getClass().getName() : null, null);
    }
}
